package com.outdd.vaietool.common.utils;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.scheduling.TriggerContext;
import org.springframework.scheduling.support.CronTrigger;

import java.lang.reflect.Field;
import java.math.BigDecimal;
import java.util.*;

/**
 * 公共的工具类
 *
 * @author vaie
 */
@Slf4j
public class BaseUtil {

    /**
     * 转换器
     *
     * @param os
     * @return
     */
    public static <T> List<T> objectsToBean(Collection<Object> os, Class<T> tClass) {

        String jsonStr = JSON.toJSONString(os);

        return JSONObject.parseArray(jsonStr, tClass);
    }

    /**
     * 转换器
     *
     * @param o
     * @return
     */
    public static <T> T objectToBean(Object o, Class<T> tClass) {

        String jsonStr = JSON.toJSONString(o);

        return JSONObject.parseObject(jsonStr, tClass);
    }


    /**
     * 转换器
     *
     * @param dto
     * @return
     */
    public static <T, DTO> T dtoTransitionT(DTO dto, Class<T> tClass) {

        String jsonStr = JSON.toJSONString(dto).replaceAll("QueryDTO", "Entity");

        return JSONObject.parseObject(jsonStr, tClass);
    }

    public static <T, DTO> List<T> dtoTransitionT(List<DTO> dtos, Class<T> tClass) {

        String jsonStr = JSON.toJSONString(dtos).replaceAll("QueryDTO", "Entity");

        return com.alibaba.fastjson.JSONObject.parseArray(jsonStr, tClass);
    }




    /**
     * 去除括号正则表达式
     */
    final static String wipeOffBrackets = "\\(.*?\\)|\\{.*?}|\\[.*?]|（.*?）";

    public static String getClassName(Class c) {
        String name = c.getName();
        return getClassName(name);
    }

    public static String getClassName(String name) {
        String className = name.substring(name.lastIndexOf(".") + 1);
        return className;
    }



    /**
     * 获取UUID
     *
     * @return
     */
    public static String getUUID() {
        return UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
    }

    /**
     * java对象转map
     *
     * @return
     */
    public static Map<String, Object> javaBeanToMap(Object bean) {
        Map<String, Object> map = new HashMap<>();
        Class<?> clazz = bean.getClass();
        for (Field field : clazz.getDeclaredFields()) {
            field.setAccessible(true);
            String fieldName = field.getName();
            Object value = null;
            try {
                value = field.get(bean);
            } catch (IllegalAccessException e) {
                e.printStackTrace();
            }
            map.put(fieldName, value);
        }
        return map;
    }



    /**
     * 首字母转小写
     *
     * @param s
     * @return
     */
    public static String toLowerCaseFirstOne(String s) {
        if (Character.isLowerCase(s.charAt(0))) {
            return s;
        }
        return (new StringBuilder()).append(Character.toLowerCase(s.charAt(0))).append(s.substring(1)).toString();


    }


    /**
     * 校验是否为corn表达式
     *
     * @param cron
     * @return
     */
    public static boolean isValidExpression(String cron) {
        TriggerContext triggerContext = new TriggerContext() {
            @Override
            public Date lastScheduledExecutionTime() {
                return null;
            }

            @Override
            public Date lastActualExecutionTime() {
                return null;
            }

            @Override
            public Date lastCompletionTime() {
                return null;
            }
        };
        Date date = null;
        try {
            CronTrigger trigger = new CronTrigger(cron);
            date = trigger.nextExecutionTime(triggerContext);
        }catch (Exception e){
            log.error("解析corn表达式异常");
        }


        return ObjectUtils.isNotEmpty(date);
    }

    /**
     * 校验是否为数字
     *
     * @param object
     * @return
     */
    public static boolean isValidInteger(Object object) {
        if (ObjectUtils.isEmpty(object)) {
            return false;
        }
        String number = object.toString();
        String regEx = "[0-9]*";
        return number.matches(regEx);
    }

    /**
     * 转换long
     *
     * @param object
     * @return
     */
    public static Long ofLong(Object object) {
        Long value = null;
        if(ObjectUtils.isEmpty(object)){
            return value;
        }
        String objectStr = object.toString();
        if(StringUtils.isNotEmpty(objectStr)
                && BaseUtil.isValidInteger(objectStr)){
            value = Long.valueOf(objectStr);
        }

        return value;
    }

    /**
     * 转换Integer
     *
     * @param object
     * @return
     */
    public static Integer ofInteger(Object object) {
        Integer value = null;
        if(ObjectUtils.isEmpty(object)){
            return value;
        }
        String objectStr = object.toString();
        if(StringUtils.isNotEmpty(objectStr)
                && BaseUtil.isValidInteger(objectStr)){
            value = Integer.valueOf(objectStr);
        }

        return value;
    }

    /**
     * 校验是否为数字
     *
     * @param object
     * @return
     */
    public static boolean isValidJSONstr(String object) {
        if (StringUtils.isEmpty(object)) {
            return false;
        }
        try {
            JSONObject.parse(object);
            return true;
        } catch (Exception e) {
            return false;
        }
    }






    /**
     * 类型装换
     *
     * @param param
     * @param aclass
     * @return
     */
    public static Object javaBeanClassConvert(Object param, Class<?> aclass) {

        if (aclass.equals(Long.class)) {

            param = BaseUtil.ofLong(param.toString());

        } else if (aclass.equals(Integer.class)) {

            param = Integer.valueOf(param.toString());

        } else if (aclass.equals(Double.class)) {

            param = Double.valueOf(param.toString());

        } else if (aclass.equals(BigDecimal.class)) {

            param = new BigDecimal(param.toString());

        }

        return param;
    }



    /**
     * 将目标对象的空串转化为NULL同时去除前后空格
     *
     * @param source
     */
    public static void setTargetNull(Object source) {

        if (source == null) {
            return;
        }

            Field[] fields = JavaReflectUtil.getFields(source.getClass());

            for (Field field : fields) {
                Object o = JavaReflectUtil.invokeGetMethod(source, field);

                if (ObjectUtils.isNotEmpty(o)) {

                    if (o.getClass().equals(String.class)) {
                        String s = o.toString().trim().replaceAll("&quot;","\"");
                         s = s.trim().replaceAll("&amp;","&");

                        if (StringUtils.isEmpty(s)) {
                            JavaReflectUtil.invokeSetMethod(source, field, null);
                        }else{
                            JavaReflectUtil.invokeSetMethod(source, field, s);
                        }
                    }

                }else{
                    JavaReflectUtil.invokeSetMethod(source, field, null);
                }
        }
    }


}
